package cn.cdu.medical.controller;

import cn.cdu.medical.entity.Medicine;
import cn.cdu.medical.service.IMedicineService;
import cn.cdu.basics.baseVo.Result;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 药品控制器
 * </p>
 */
@Slf4j
@RestController
@RequestMapping("/zwz/medicine")
@Tag(name = "药品管理接口")
public class MedicineController {

    @Autowired
    private IMedicineService medicineService;

    @GetMapping("/frequent")
    @Operation(summary = "获取常用药品列表")
    public Result<List<Medicine>> getFrequentMedicines() {
        log.info("获取常用药品列表");
        try {
            List<Medicine> medicines = medicineService.getFrequentMedicines();
            return Result.success(medicines);
        } catch (Exception e) {
            log.error("获取常用药品列表失败", e);
            return Result.error("获取常用药品列表失败");
        }
    }

    @GetMapping("/search")
    @Operation(summary = "搜索药品")
    public Result<List<Medicine>> searchMedicines(@RequestParam String name) {
        try {
            if (StringUtils.isBlank(name)) {
                return Result.error("搜索关键词不能为空");
            }
            
            String trimmedName = name.trim();
            if (trimmedName.length() < 1) {
                return Result.error("搜索关键词长度不能小于1个字符");
            }
            
            List<Medicine> medicines = medicineService.searchMedicinesByName(trimmedName);
            if (medicines.isEmpty()) {
                return Result.success(medicines, "未找到匹配的药品");
            }
            return Result.success(medicines);
        } catch (Exception e) {
            log.error("搜索药品失败", e);
            return Result.error("搜索药品时发生错误: " + e.getMessage());
        }
    }
} 